using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Client;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace Net8.Identity.MvcClient.Extensions
{
    public static class RegisterServices
    {
        public static WebApplicationBuilder SetupServices(this WebApplicationBuilder builder)
        {
            // 从配置文件中读取密钥和设置
            var openIddictIssuer = builder.Configuration["OpenIddict:Issuer"] ?? "https://localhost:7031/";
            var openIddictClientId = builder.Configuration["OpenIddict:ClientId"] ?? "mvc";
            var openIddictClientSecret = builder.Configuration["OpenIddict:ClientSecret"] ?? "901564A5-E7FE-42CB-B10D-61EF6A8F3654";
            var openIddictRedirectUri = builder.Configuration["OpenIddict:RedirectUri"] ?? "callback/login/local";
            var openIddictPostLogoutRedirectUri = builder.Configuration["OpenIddict:PostLogoutRedirectUri"] ?? "callback/logout/local";
            var dbConnectionString = builder.Configuration.GetConnectionString("DbFilePath") ?? "Data Source=Dbfile/mvcclient.db";

            builder.Services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlite(dbConnectionString);
                options.UseOpenIddict();
            });

            builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/login";
                options.LogoutPath = "/logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(50);
                options.SlidingExpiration = false;
            });

            builder.Services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                })
                .AddClient(options =>
                {
                    // 启用授权码支持
                    options.AllowAuthorizationCodeFlow();
                    
                    // 使用开发环境下的临时密钥（生产环境请使用持久化证书）
                    options.AddDevelopmentEncryptionCertificate()
                        .AddDevelopmentSigningCertificate();

                    options.UseAspNetCore()
                       // 启用状态码
                       .EnableStatusCodePagesIntegration()
                       // 启用重定向回调
                       .EnableRedirectionEndpointPassthrough()
                       // 启用注销回调
                       .EnablePostLogoutRedirectionEndpointPassthrough();

                    options.UseSystemNetHttp()
                        .SetProductInformation(typeof(Program).Assembly);

                    // 添加与服务器项目中的客户端应用程序定义匹配的客户端注册。
                    options.AddRegistration(new OpenIddictClientRegistration
                    {
                        Issuer = new Uri(openIddictIssuer, UriKind.Absolute),
                        ClientId = openIddictClientId,
                        ClientSecret = openIddictClientSecret,
                        Scopes = { Scopes.Email, Scopes.Profile },
                        RedirectUri = new Uri(openIddictRedirectUri, UriKind.Relative),
                        PostLogoutRedirectUri = new Uri(openIddictPostLogoutRedirectUri, UriKind.Relative)
                    });
                });

            builder.Services.AddHttpClient();
            builder.Services.AddControllersWithViews();

            // 写入种子数据
            builder.Services.AddHostedService<Worker>();
            return builder;
        }
    }
}